package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.EmployeeService;
import com.itheima.reggie.service.impl.EmployeeServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录功能
     * @param employee
     * @param request
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {
        //1.判断用户是否存在
        //2.用select sql语句查询是否存在这个用户
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Employee::getUsername,employee.getUsername());//查询语句放service里面
        Employee emp = employeeService.getOne(lambdaQueryWrapper);
        if (emp==null){
            return R.error("用户不存在"); //为空代表用户不存在,直接返回
        }
        //3.用户名存在,开始判断密码
        //先对明文加密,再与数据库中加密了的密码进行比对
        String sqlsalt= emp.getPassword().substring(32);
        String miwen=DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex(employee.getPassword().getBytes())+sqlsalt).getBytes())+sqlsalt;
        if (!emp.getPassword().equals(miwen)){
            return R.error("密码错误");//比对不正确直接返回
        }
        //4.还要判断状态是否被禁用
        if (emp.getStatus()==0){
            return R.error("该用户被禁用");
        }
        //经过以上比对,都正确才返回正确
        request.getSession().setAttribute("employee",emp);
        return R.success(emp);
    }

    /**
     * 退出功能
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpServletRequest request) {
        //退出就是将存储的Session消息删除
        request.getSession().removeAttribute("employee");
        return R.success(null);
    }

    /**
     * 添加用户操作
     * @param employee
     * @param request
     * @return
     */
    @PostMapping
    public R save(@RequestBody Employee employee,HttpServletRequest request){
        //1.设置添加时间
        employee.setCreateTime(LocalDateTime.now());
        //2.设置修改时间
        employee.setUpdateTime(LocalDateTime.now());
        //3.设置添加人
        Employee emp = (Employee) request.getSession().getAttribute("employee");
        Long id = emp.getId();
        employee.setCreateUser(id);
        //4.设置修改人
        employee.setUpdateUser(id);
        String sqlsalt = UUID.randomUUID().toString().replace("-", "");
        //5.设置初始化密码(加密)
        employee.setPassword(DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex("123456".getBytes())+sqlsalt).getBytes())+sqlsalt);
        //6.调用方法添加员工
        employeeService.save(employee);
        //7.用户名唯一时需要定义全局异常捕获并将错误信息返回给页面
        return R.success(null);
    }
    /**
     * 分页
     */
    @GetMapping("/page")
    public R<Page<Employee>> page(int page,int pageSize,String name){
        //1.创建一个分页对象
        Page<Employee> pageInfo = new Page<>(page,pageSize);
        //2.分页查询上面还有一个按名字查询的查询条件
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //无论查不查询名字,都按照最新修改时间来排序
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //调用方法分页!!!还需要分页插件 mybatisplusconfig
        employeeService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }


    /**
     * 通用修改方法
     * @param employee
     * @param
     * @return
     */
    @PutMapping
    public R update(@RequestBody Employee employee){
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
       // Employee emp = (Employee) request.getSession().getAttribute("employee");
//        Long id = emp.getId();
//        employee.setUpdateUser(id);
        employeeService.updateById(employee);
        return R.success(null);
    }

//    /**
//     * 回显数据
//     * @param id
//     * @return
//     */
//    @GetMapping("/{id}")//前端是路径传参
//    public R<Employee> selectById(@PathVariable Long id){
//        Employee employee = employeeService.getById(id);
//        if (employee!=null){
//            return R.success(employee);
//        }
//        return R.error("用户不存在");
//    }
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        Employee emp = employeeService.getById(id);
        return R.success(emp);
    }
}
